<?php
# autoHTML: the dynamic PHP5 library for fast website prototyping
# http://code.google.com/p/autohtml/
#
# Copyright (c) 2010, Shu Zong Chen
# http://freelanceDreams.com/
# All rights reserved. 
# 
# Redistribution and use in source and binary forms, with or without 
# modification, are permitted provided that the following conditions are met: 
# 
#  * Redistributions of source code must retain the above copyright notice, 
#    this list of conditions and the following disclaimer. 
#  * Redistributions in binary form must reproduce the above copyright 
#    notice, this list of conditions and the following disclaimer in the 
#    documentation and/or other materials provided with the distribution. 
#  * Neither the name of autoHTML nor the names of its contributors 
#    may be used to endorse or promote products derived from this software 
#    without specific prior written permission. 
# 
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
# POSSIBILITY OF SUCH DAMAGE.

class AUTO_SQL{
	var $LINK;
	var $CONFIG;

	//METHODS
	function connect(){
		$this->LINK = mysql_connect($this->CONFIG["hostname"], $this->CONFIG["username"], $this->CONFIG["password"]);
		if ($this->LINK){
			mysql_select_db($this->CONFIG["database"]);
			mysql_query("SET NAMES utf8");
			return true;
		}else{
			echo "FAIL! Could not connect to database.  kthxbye!\n";
			return false;
		}
		return false;
	}
	function query($query){
		$results = mysql_query($query);
		if (!$results) {
			echo "FAIL! " . mysql_error() . " kthxbye\n";
			return false;
		}
		$return = array();
		$numrows=0;
		while ($row = mysql_fetch_assoc($results)){
			array_push($return, $row);
			$numrows++;
		}
		return array("results"=>$return, "numrows"=>$numrows);
	}
	function __construct(){
		$this->CONFIG["hostname"]="localhost";
		$this->CONFIG["username"]="username";
		$this->CONFIG["password"]="password";
		$this->CONFIG["database"]="database";
	}
	//-----------------------------------------------------------------------
	//HIDDEN METHODS
	//------------------------------------------------------------------------
}

class AUTO_QUERY{
	//CONFIGURATION
	var $CONFIG;
	var $TABLE;
	//RECORD INFORMATION
	var $INDEX;
	var $FIELDS;
	var $PASSWORD;
	//INTERFACE
	var $INPUTS;
	var $RESULTS;
	var $ERRORS;
	function __toString(){
		return $this->RealizeQuery();
	}
	function setIndex($name, $type, $max=0, $min=0){
		$array = array("name"=>$name, "label"=>$label, "type"=>$type, "max"=>$max, "min"=>$min);
		if (sizeof($this->INDEX)==0){
			$this->INDEX = $array;
		}else{
			echo "FAIL! Error already set.";
		}
	}
	function setPassword($name, $type, $max=0, $min=0){
		$array = array("name"=>$name, "label"=>$label, "type"=>$type, "max"=>$max, "min"=>$min);
		if (sizeof($this->PASSWORD)==0){
			$this->PASSWORD = $array;
		}else{
			echo "FAIL! Password already set.";
		}
	}
	function overrideIndex($name, $type, $max=0, $min=0){
		$array = array("name"=>$name, "label"=>$label, "type"=>$type, "max"=>$max, "min"=>$min);
		$this->INDEX = $array;
	}
	function defaultSortOn($field, $sort){
		$this->CONFIG["sort"]["default"] = array("field"=>$field, "sort"=>$sort);
	}
	function clearSort(){
		$this->CONFIG["sort"]["custom"] = array();
	}
	function setSortOn($field, $sort){
		$this->CONFIG["sort"]["custom"] = array();
		$this->addSortOn($field, $sort);
	}
	function addSortOn($field, $sort){
		array_push($this->CONFIG["sort"]["custom"], array("field"=>$field, "sort"=>$sort));
	}
	function addField($name, $label, $type="_VARCHAR", $max=0, $min=0){
		$array = array("name"=>$name, "label"=>$label, "type"=>$type, "max"=>$max, "min"=>$min);
		$this->FIELDS[$name] = $array;
	}
	function FetchQuery($type, $id, $field=null){
		$result = mysql_query($this->RealizeQuery($type, $id, $field));
		$return = array();
		$i=0;
		while ($row = mysql_fetch_assoc($result)){
			$return["$i"] = $row;
			$i++;
		}
		return array("results"=>$return, "numrows"=>$i);
	}
	function UpdatePassword($id, $password, $verify){
		if (isset($password) && isset($verify)){
			if ($password === $verify){
				$check = check_input($password, $this->PASSWORD["type"], $this->PASSWORD["max"], $this->PASSWORD["min"]);
				if ($check["answer"]===true){
					$password = mysql_real_escape_string($password);
					$id = mysql_real_escape_string($id);
					$query = "UPDATE {$this->TABLE} SET password=\"$password\" WHERE {$this->INDEX["name"]} = $id LIMIT 1";
					mysql_query($query) or die(mysql_error());
					return true;
				}else{
					foreach ($check["error"] as $value){
						array_push($this->ERRORS, ($value));
					}
					return false;
				}
			}else{
				array_push($this->ERRORS, "Password and confirmation do not match");
				return false;
			}
		}else{
			array_push($this->ERRORS, "Password and confirmation do not match");
			return false;
		}
		array_push($this->ERRORS, "Unknown error occured attempting to change password");
		return false;
	}
	function ClearInput(){
		$this->INPUTS = array();
		return true;
	}
	function NewInput($input){
		$this->ClearInput();
		return $this->RegisterInput($input);
	}
	function RegisterInput($input){
		foreach ($input as $key=>$value){
			if (isset($this->FIELDS[$key])){
				$check = check_input($value, $this->FIELDS[$key]["type"], $this->FIELDS[$key]["max"], $this->FIELDS[$key]["min"]);
				if ($check["answer"] === true){
					$this->INPUTS[$key] = $value;
				}else{
					foreach ($check["error"] as $value){
						array_push($this->ERRORS, ($this->FIELDS[$key]["label"]).": $value");
					}
				}
			}
		}
		return true;
	}
	function ErrorCheck(){
		if (sizeof($this->ERRORS)==0){
			echo "No errors";
			return true;
		}else{
			echo "<div id=\"errors\">\n";
			foreach ($this->ERRORS as $key=>$value){
				echo "$value<br />\n";
			}
			echo "</div>\n";
		}
		return false;
	}
	function AttemptUpdate($id){
		if (sizeof($this->ERRORS)==0){

			$fields = array();
			foreach ($this->INPUTS as $key=>$value){
				$fields[$key] = "$key = \"" . mysql_real_escape_string($value) . "\"";
			}
			$fields = implode(", ", $fields);
			$query = "UPDATE {$this->TABLE} SET $fields WHERE {$this->INDEX["name"]} = \"$id\" LIMIT 1";
//			echo $query;
			mysql_query($query);
			return true;
		}else{
			echo "<div id=\"errors\">\n";
			foreach ($this->ERRORS as $key=>$value){
				echo "$value<br />\n";
			}
			echo "</div>\n";
		}
		return false;
	}
	function CustomSelectQuery($query){
		return mysql_query("SELECT * FROM {$this->TABLE} WHERE $query");
	}
	function DoQuery($type="SELECT", $id=null, $field=null){
		return mysql_query($this->RealizeQuery($type, $id, $field));
	}
	function RealizeQuery($type="SELECT", $id=null, $field=null){
		if ($field===null){
			$field = $this->INDEX["name"];
		}
		$TARGET = mysql_real_escape_string($id);

		$fields = array();
		foreach ($this->INPUTS as $key=>$value){
			$fields[$key] = "$key = \"" . mysql_real_escape_string($value) . "\"";
		}
		$fields = implode(", ", $fields);
	
		$table = $this->TABLE;
		switch ($type){
			case "SELECT":
				//Set order rules
					$b = array();
					if (count($this->CONFIG["sort"]["custom"])){
						$a = $this->CONFIG["sort"]["custom"];
					}else{
						$a = array($this->CONFIG["sort"]["default"]);
					}
					foreach ($a as $value){
						array_push($b, "{$value["field"]} {$value["sort"]}");
					}
					$order = "ORDER BY " . implode(", ", $b);
				//end order rules
							
				$query = "SELECT * FROM {$this->TABLE} WHERE $field = \"$TARGET\" $order";
				break;
			case "UPDATE":
				$query = "UPDATE {$this->TABLE} SET $fields WHERE {$this->INDEX["name"]} = \"$TARGET\" LIMIT 1";
				break;
			case "INSERT":
				$query = "INSERT INTO {$this->TABLE} SET $fields";
				break;
			case "DELETE":
				$query = "DELETE FROM {$this->TABLE} WHERE {$this->INDEX["name"]} = \"$TARGET\" LIMIT 1";
				break;
			default:
				echo "FAIL!: Wrong method [{$this->METHOD}] used.  Kthxbye.\n";
				break;
		}
		//echo $query;
		return $query;
	}
	function __construct(){
		$this->FIELDS = array();
		$this->CONFIG = array();
			$this->CONFIG["sort"] = array("default"=>array("field"=>"id", "sort"=>"ASC"), "custom"=>array());
		$this->INDEX = array();
		$this->PASSWORD = array();
		$this->INPUTS = array();
		$this->ERRORS = array();
	}
}